// package-common/pages/share-apply-distributor/index.js
const app = getApp();
import { COMMON_PAGE, PACKAGE_STORE_PAGE } from '../../../constants/route';
import { setTitle, tipToast, navBack, navTo, showLoading, hideLoading, subscribeMessage } from '../../../common/env';
import { UserInfoUpdateMixins, PageOssMixins } from '../../../behaviors/page';
import { DISTRIBUTOR_APPLY_FIELD } from '../../../constants/manage';
import { MESSAGE_ID } from '../../../constants/message';
import { getDistributeRequest, saveDistributeRequest} from '../../../api/usr';
import { getShareBrandInfo, getConfig } from '../../../api/common';
let loaded = false, brandId;

Page({
    mixins: [UserInfoUpdateMixins, PageOssMixins],
    data: {
        brandInfo: null,
        requestInfo: null,
        applyFields: {},
        applyFieldMap: DISTRIBUTOR_APPLY_FIELD,
        bindMobileGuidePopup: {
            show: false,
        },
        userConfig: {},
    },
    onLoad(options) {
        brandId = options.brandId;
    },
    async onShow() {
        const config = await getConfig();
        this.setData({ userConfig: config });
        if (!app.globalData.isReadyAuth) {
            const _ = this;
            const originFunc = app.userIdentifyCallback;
            app.userIdentifyCallback = function (...args) {
                _.onShow(...args);
                return originFunc && originFunc(...args);
            }
            return;
        } else {
            const { mobile, nickName = '' } = this.data.userInfo;
            mobile && this.setData({
                'applyFields.mobile': mobile,
                'applyFields.nick_name': nickName,
            });
            !loaded && showLoading('加载中...');
            await this._handleGetBrandInfo();
            await this._handleGetDistributorSetting();
            if (!loaded) hideLoading(); loaded = true;
        }
    },
    async _handleGetBrandInfo() {
        const brandInfo = await getShareBrandInfo(brandId);
        this.setData({ brandInfo });
        setTitle(brandInfo.name);
    },
    async _handleGetDistributorSetting() {
        const requestInfo = await getDistributeRequest(brandId);
        this.setData({ requestInfo });
    },
    handleChange(e) {
        const { key } = e.currentTarget.dataset;
        const value = e.detail;
        const { applyFields } = this.data;
        applyFields[key] = value;
        this.setData({ applyFields });
    },
    handleShowMobileSellect() {
        const { userInfo } = this.data;
        if (!userInfo || !userInfo.mobile) {
            this.setData({
                'bindMobileGuidePopup.show': true,
            });
        }
    },
    handleGetMobile(e) {
        const { mobile } = e.detail;
        this.setData({
            'applyFields.mobile': mobile,
        });
    },
    async handleApply() {
        const { requestInfo, applyFields } = this.data;
        const { applyInfoFields } = requestInfo;
        if (!applyFields.nick_name) {
            tipToast('请输入姓名');
            return;
        } else if (!applyFields.mobile) {
            tipToast('请设置手机号');
            return;
        } else if (applyInfoFields.indexOf('wechat_id') > -1 && !applyFields.wechat_id) {
            tipToast('请输入微信号');
            return;
        } else if (applyInfoFields.indexOf('remark') > -1 && !applyFields.remark) {
            tipToast('请输入留言');
            return;
        }
        const result = await saveDistributeRequest({ brandId, applyFields: JSON.stringify(applyFields) });
        if (result) {
            this.setData({
                requestInfo: {
                    ...requestInfo,
                    ...result,
                },
            });
            subscribeMessage([MESSAGE_ID.distributor_audit]);
        }
    },
    handleReApply() {
        this.setData({
            'requestInfo.auditResult': '',
        });
    },
    handleAttention() {
        navTo(COMMON_PAGE['webview'], {
            url: this.data.userConfig.aboutUrl,
        });
    },
    handleOpen() {
        const { distributorId } = this.data.requestInfo;
        navTo(PACKAGE_STORE_PAGE['storeOpen'], {
            brandId,
            distributorId,
        });
    },
    handleBack() {
        const pages = getCurrentPages();
        if (pages.length <= 1) {
            navTo(COMMON_PAGE['shareBrand'], {
                brandId,
            });
        } else {
            navBack();
        }
    },
})
